package com.zx.mvcframework.handle.interceptor;

import com.zx.mvcframework.annotations.Security;
import com.zx.mvcframework.handle.InterceptorHandler;
import com.zx.mvcframework.handle.MethodHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @ProjectName: myspring
 * @Package: com.zx.mvcframework.handle.interceptor
 * @ClassName: SecurityInterceptor
 * @Author: xzl
 * @Description:  权限拦截器
 * @Date: 2021/10/4 17:55
 */
public class SecurityInterceptor implements InterceptorHandler {

    /**
     * 用户标识
     */
    private  final static  String IDENTIFY ="username";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, MethodHandler handler) throws Exception {
        //1.是否需要验证
        Security security = getSecurity(handler.getControllerType(), handler.getMethod());
        if(security == null || security.value().length <1){
            return true;
        }
        //2.获取请求里的用户信息
        String parameter = request.getParameter(IDENTIFY);

        if(parameter == null || "".equals(parameter)){
            result(response);
            return false;
        }

        //3.判断是否有权限
        if(notExist(security.value(),parameter)){
            result(response);
            return false;
        }
        return true;
    }


    /**
     * 无权限 返回401
     */
    public  void result(HttpServletResponse response) throws IOException {
        response.setHeader("content-type", "text/html;charset=utf-8");
        response.getWriter().println("401");
    }

    /**
     * 如果方法上有 @Security则以方法上为准
     * 无 则从类上查找
     */
    public Security getSecurity(Class  tClass, Method method){
        if( method.isAnnotationPresent(Security.class)){
            return method.getAnnotation(Security.class);
        }else if(tClass.isAnnotationPresent(Security.class)){
            return (Security) tClass.getAnnotation(Security.class);
        }else {
            return null;
        }
    }


    private boolean notExist(String[] ss ,String target){
        for (String str:ss
        ) {
            if(str.equals(target)) return false;
        }
        return  true;
    }
}
